# -*- coding: utf-8 -*-
import os
import time

from annoying.decorators import render_to
from django.contrib.auth.decorators import login_required

from django.http import HttpResponseRedirect
from django.views.generic import ListView
from django.utils.translation import ugettext as _

from mediabox.lira.models import Document, File

from mediabox.lira.forms import UploadForm
from mediabox.lira.forms import DocumentForm
from mediabox.lira.utils import Transliterator
from mediabox.lira.utils import set_messages
from mediabox.lira.utils import get_msgfile
from mediabox.lira.utils import make_dirs

from django.conf import settings

class Uploader:
    def __init__(self, upfile):
        self.upfile = upfile

    def upload(self, where=None):
        self.where = where
        return self._handle_file()

    # TODO: Refactor from here, below full crap
    def _handle_file(self):
        """ TODO: perform checks if self.where is not None """
        saved_filename  = os.path.join(settings.MEDIA_ROOT, self.where, self.upfile.name)

        tmpfile = open(saved_filename, 'wb+')

        for chunk in self.upfile.chunks():
            tmpfile.write(chunk)

        tmpfile.close()

        saveindb = File()
        saveindb.filemime = self.upfile.content_type
        saveindb.filename = self.upfile.name
        saveindb.filesize = self.upfile.size
        saveindb.timestamp = time.time()
        saveindb.status = 0
        saveindb.uri = saved_filename
        saveindb.save()

        return saveindb

    def _generate_temp_filename(self):
        return os.path.join(settings.FILE_UPLOAD_TEMP_DIR, str(int(time.time())))

@login_required
@render_to('documents/manage/document_new.html')
def CreateDocument(request):
    form = DocumentForm(request.POST or None)
    messages = [{'type': 'message info', 'message': _('Please fill out all fields'), }]

    if form.is_valid() and request.FILES:
        obj = form.save()
        upload_manager = Uploader(upfile=request.FILES['upload'])

        # Create folder structure for program
        upload_path = Transliterator.cleancyrillic(obj.program.title)
        upload_path = os.path.join(settings.MEDIA_ROOT, upload_path)
        if not os.path.exists(os.path.join(settings.MEDIA_ROOT, upload_path)):
            make_dirs(upload_path)

        # Create folder for a given region
        belongs2region = Transliterator.cleancyrillic(obj.region.region_name)
        upload_path = os.path.join(upload_path, obj.item_type, belongs2region)
        if not os.path.exists(upload_path):
            os.makedirs(upload_path, 0775)

        file_id = upload_manager.upload(where=upload_path)
        doc = Document.objects.get(pk=obj.pk)
        doc.myfile = file_id
        doc.owner = request.user
        doc.save()

        msg_filename = get_msgfile(request)
        messages = [{'type': 'success', 'message': _('Document saved'), }]

        if set_messages(filename=msg_filename, messages=messages):
            request.session['msg_file'] = msg_filename

        return HttpResponseRedirect('/manage/documents')
    elif 'POST' in request.method and not form.is_valid():
        msg_filename = get_msgfile(request)

        if set_messages(filename=msg_filename, messages=messages):
            request.session['msg_file'] = msg_filename

    print form

    return {
        'upload_form': UploadForm(),
        'form': form,
        'system_messages': messages
    }

class DocumentList(ListView):
    template_name = 'documents/manage/document_list.html'
    model = Document
    context_object_name = 'documents'
    queryset = Document.objects.filter(item_type='document')

class PictureList(ListView):
    template_name = 'documents/manage/pictures_list.html'
    model = Document
    context_object_name = 'pictures'
    queryset = Document.objects.filter(item_type='picture')

class VideoList(ListView):
    template_name = 'documents/manage/videos_list.html'
    model = Document
    context_object_name = 'videos'
    queryset = Document.objects.filter(item_type='video')

class OtherList(ListView):
    template_name = 'documents/manage/others_list.html'
    model = Document
    context_object_name = 'others'
    queryset = Document.objects.filter(item_type='others')
